//
//  XDNetworkRequset.m
//  LNCashLoans
//
//  Created by kms on 2019/4/8.
//  Copyright © 2019 淘发现1iOS. All rights reserved.
//

#import "XDNetworkRequset.h"

@implementation XDNetworkRequset
static NSString *boundary=@"AlvinLeonPostRequest";

+ (void)PostNetwork:(NSString *)urlString andParam:(NSDictionary *)param completionBlock:(void (^)(BOOL, NSDictionary *))completeBlock
{

    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 设置可接受数据类型
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 50.0;
    // 设置语言
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    if ([currentLanguage containsString:@"zh"] && ([currentLanguage containsString:@"HK"] || [currentLanguage containsString:@"TW"])) {
        [sessionManager.requestSerializer setValue:@"hk" forHTTPHeaderField:@"language"];
    } else if ([currentLanguage containsString:@"zh"] && ([currentLanguage containsString:@"CN"] || [currentLanguage containsString:@"US"])){
        [sessionManager.requestSerializer setValue:@"cn" forHTTPHeaderField:@"language"];
    } else {
        [sessionManager.requestSerializer setValue:@"en" forHTTPHeaderField:@"language"];
    }
    //    appVersionNum：当前应用软件版本 （Build版本号）
    //system:ios、Android
    //phoneVersion:手机系统版本

    // 取手机系统版本号，知道写就行了，不用特意去记
    NSString *versionNum = [[UIDevice currentDevice] systemVersion];
    [sessionManager.requestSerializer setValue:versionNum forHTTPHeaderField:@"phoneVersion"];
    // 获取app的版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    [sessionManager.requestSerializer setValue:[NSString stringWithFormat:@"%@(%@)", app_Version, app_build] forHTTPHeaderField:@"appVersionNum"];
    [sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"system"];
    [sessionManager POST:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject != nil) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                completeBlock(YES, responseObject);
            } else if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                completeBlock(YES, dict);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        completeBlock(NO, nil);
    }];
}

+ (void)PostNetworkREQ:(NSString *)urlString andParam:(NSDictionary *)param completionBlock:(void (^)(BOOL, NSDictionary *))completeBlock
{

    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 设置可接受数据类型
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    // 设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 30.0;
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置语言
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    if ([currentLanguage containsString:@"zh"] && ([currentLanguage containsString:@"HK"] || [currentLanguage containsString:@"TW"])) {
        [sessionManager.requestSerializer setValue:@"hk" forHTTPHeaderField:@"language"];
    } else if ([currentLanguage containsString:@"zh"] && ([currentLanguage containsString:@"CN"] || [currentLanguage containsString:@"US"])){
        [sessionManager.requestSerializer setValue:@"cn" forHTTPHeaderField:@"language"];
    } else {
        [sessionManager.requestSerializer setValue:@"en" forHTTPHeaderField:@"language"];
    }
    //    appVersionNum：当前应用软件版本 （Build版本号）
    //system:ios、Android
    //phoneVersion:手机系统版本

    // 取手机系统版本号，知道写就行了，不用特意去记
    NSString *versionNum = [[UIDevice currentDevice] systemVersion];
    [sessionManager.requestSerializer setValue:versionNum forHTTPHeaderField:@"phoneVersion"];
    // 获取app的版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    [sessionManager.requestSerializer setValue:[NSString stringWithFormat:@"%@(%@)", app_Version, app_build] forHTTPHeaderField:@"appVersionNum"];
    [sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"system"];
    [sessionManager POST:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject != nil) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                completeBlock(YES, responseObject);
            } else if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                completeBlock(YES, dict);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        completeBlock(NO, nil);
    }];
}

+ (void)GetNetwork:(NSString *)urlString andParam:(NSString *)param completionBlock:(void (^)(BOOL, NSDictionary *))completeBlock
{
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 设置可接受数据类型
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    // 设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 30.0;
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager GET:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject != nil) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                completeBlock(YES, responseObject);
            } else if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                completeBlock(YES, dict);
            } else if ([responseObject isKindOfClass:[NSString class]]) {

            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        completeBlock(NO, nil);
    }];

}

+ (void)GetNetworkRequest:(NSString *)urlString andParam:(NSString *)param completionBlock:(void(^)(BOOL success, NSArray *jsonArr))completeBlock
{
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 设置可接受数据类型
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    // 设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 30.0;
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager GET:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject != nil) {
            if ([responseObject isKindOfClass:[NSArray class]]) {
                completeBlock(YES, responseObject);
            } else if ([responseObject isKindOfClass:[NSData class]]) {
                id  arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                completeBlock(YES, arr);
            } else if ([responseObject isKindOfClass:[NSString class]]) {

            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        completeBlock(NO, nil);
    }];
}

+(void)postNETworkRequest:(NSString *)urlString andParam:(NSString *)param completionBlock:(void(^)(BOOL success, NSDictionary *jsonObject))completeBlock
{
    NSURL *URL=[NSURL URLWithString:urlString];//不需要传递参数
    //    2.创建请求对象

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求

    request.timeoutInterval=60.0;//设置请求超时为5秒

    request.HTTPMethod=@"POST";//设置请求方法

    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];

    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 设置可接受数据类型
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    // 设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 30.0;
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"122");
        if (responseObject != nil) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                completeBlock(YES, responseObject);
            } else if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                completeBlock(YES, dict);
            } else if ([responseObject isKindOfClass:[NSString class]]) {

            }
        } else {
            completeBlock(NO, nil);
        }
    }];
}

+ (void)PostStringNetwork:(NSString *)urlString andParam:(NSString *)param completionBlock:(void(^)(BOOL success, NSDictionary *jsonObject))completeBlock
{
    NSURL *URL=[NSURL URLWithString:urlString];//不需要传递参数
    //    2.创建请求对象

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求

    request.timeoutInterval=60.0;//设置请求超时为5秒

    request.HTTPMethod=@"POST";//设置请求方法

    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSError* error ;
    if (data) {
        NSDictionary *serverResignInfoDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];


        completeBlock(YES, serverResignInfoDic);
    } else {
        completeBlock(NO, nil);
    }

}


+ (void)GetNetworkString:(NSString *)urlString andParam:(NSString *)param completionBlock:(void (^)(BOOL, NSData *))completeBlock
{
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 设置可接受数据类型
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    // 设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 30.0;
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager GET:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject != nil) {
            if ([responseObject isKindOfClass:[NSString class]]) {
                completeBlock(YES, responseObject);
            } else if ([responseObject isKindOfClass:[NSData class]]) {
                completeBlock(YES, responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        completeBlock(NO, nil);
    }];

}
+ (void)ReqFile_HTTP:(NSString *)req_URL fileData:(NSData *)fileData andParam:(NSDictionary *)param fileName:(NSString *)fileName fileType:(NSString *)fileType completeBloc:(void (^)(BOOL, NSDictionary *))completeBlock
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //    configuration.HTTPAdditionalHeaders = @{@"Content-Type" : @"multipart/form-data"};
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager]initWithSessionConfiguration:configuration];
    // 设置可接受数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:req_URL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传filename
        [formData appendPartWithFileData:fileData name:@"file" fileName:[NSString stringWithFormat:@"%@.jpg", fileName] mimeType:[NSString stringWithFormat:@"image/%@", fileType]];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject != nil) {
            NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"json ---- %@",jsonObject);
            completeBlock(YES, jsonObject);
        }else {
            completeBlock(NO, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error  ==  %@",error);
        completeBlock(NO, nil);
    }];
}

+ (UIImage *) imageFromURLString: (NSString *) urlstring
{
    // This call is synchronous and blocking
    return [UIImage imageWithData:[NSData
                                   dataWithContentsOfURL:[NSURL URLWithString:urlstring]]];
}

//+ (void)setImageWithImageView:(UIImageView *)imageView WithUrlString:(NSString *)urlString WithImageQualist:(ImageQuality)imageQuality
//{
//    urlString = [urlString stringByAppendingString:[NSString stringWithFormat:@"?/q/%ld", imageQuality]];
////    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] completed:^(UIImage * _Nullable image, NSError * _Nullable error, EMSDImageCacheType cacheType, NSURL * _Nullable imageURL) {
////
////    }];
////    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString]];
//    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] completed:^(UIImage *image, NSError *error, EMSDImageCacheType cacheType, NSURL *imageURL) {
////        NSLog(@"%@", error);
//    }];
//}

//+ (void)setImagelimWithImageView:(UIImageView *)imageView WithUrlString:(NSString *)urlString
//{
//    urlString = [urlString stringByAppendingString:@"?imageslim"];
//
//    //    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString]];
////    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] completed:^(UIImage *image, NSError *error, EMSDImageCacheType cacheType, NSURL *imageURL) {
////        NSLog(@"%@", error);
////    }];
//}

@end
